/**
 * @Description: 推荐有礼
 * @author ourslookAdmin
 * @date 2019-04-19 16:30:44
 */
import React, { Fragment } from 'react';
import 'braft-editor/dist/index.css';
import BraftEditor from 'braft-editor';
import {
  Button,
  Card,
  Checkbox,
  Col,
  Divider,
  Form,
  Input,
  InputNumber,
  Radio,
  Row,
  Select,
  Spin,
  Tag,
  TreeSelect,
  BackTop,
  DatePicker,
  Upload,
  Icon,
  Switch,
  Tooltip,
  List,
  Drawer,
  Table,
} from 'antd';
import moment from 'moment';
import { formatMessage, FormattedMessage } from 'umi/locale';
import 'antd/dist/antd.css';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import { requestLists, requestPromise } from '@/utils/request';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import InputColor from 'react-input-color';
import Modal from 'drag-modal';
import Highlighter from 'react-highlight-words';
import numeral from 'numeral';
import BaseForm from '../../../components/ourslook/BaseForm';
import ETable from '../../../components/ourslook/ETable';
import { getWebPath } from '../../../utils/request';
import uiUtils, { hasPermission, rulesReg, rulesRemote } from '../../../utils/uiUtils';
import styles from '../../../utils/ourslook.less';
import { handleEditorupload, editorPreview,editorProps } from '../../../utils/braft_editor_config';
import Ellipsis from '../../../components/ourslook/Ellipsis';
import DefaultImage from '../../../components/ourslook/DefaultImage';

const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const TextArea = Input.TextArea;
const Password = Input.Password;
const CheckboxGroup = Checkbox.Group;
const { MonthPicker, RangePicker, WeekPicker } = DatePicker;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

// @coming({title: '精彩即将呈现！', value: Date.now() + 1000 * 60 * 60 * 24 * 2})
@connect(() => ({}))
class Recommend extends React.Component {
  params = {
    page: 1,
    limit: 10,
  };

  formItemLayout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
  };

  /**
   * https://ant-design.gitee.io/components/table-cn/
   *
   * 需要指定 column 的 width 属性，否则列头和内容可能不对齐。（必须留一列不设宽度或者minWidth以适应弹性布局）
   * 建议指定 scroll.x 为大于表格宽度的固定值或百分比。注意，且非固定列宽度之和不要超过 scroll.x, 一般无table正常展开的宽度
   * 未知长度字段或者字符特别多的字段不要放置在列表
   */
  columns = [
    {
      title: '',
      width: 30,
      align: 'center',
      fixed: 'left',
      render: (value, record, index) => index + 1,
    },
    {
      title: '推荐有礼名称',
      dataIndex: 'recommendName',
      align: 'center',
      sorter: false,
      render: value => (
        <Ellipsis length={10} tooltip>
          {value}
        </Ellipsis>
      ),
    },
    {
      title: '赠品名称',
      dataIndex: 'giftName',
      width: 180,
      align: 'center',
      sorter: false,
      render: value => (
        <Ellipsis length={10} tooltip>
          {value}
        </Ellipsis>
      ),
    },
    {
      title: '赠品商品名称',
      dataIndex: 'productName',
      width: 180,
      align: 'center',
      sorter: false,
      render: value => (
        <Ellipsis length={10} tooltip>
          {value}
        </Ellipsis>
      ),
    },
    {
      title: '背景颜色',
      dataIndex: 'bgColor',
      width: 150,
      align: 'center',
      sorter: false,
      render: (value, record, index) => (
        <InputColor initialHexColor={record.bgColor} placement="right" />
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 120,
      align: 'center',
      sorter: false,
      render: (value, record, index) => (
        <React.Fragment>
          <div>
            <Switch
              checkedChildren="启用"
              unCheckedChildren="禁用"
              onChange={val => {
                this.setStateByTableColume(record, index);
                this.updateStatus(val);
              }}
              checked={value === 1}
            />
          </div>
        </React.Fragment>
      ),
    },
    {
      title: '微信二维码',
      dataIndex: 'wxQrCode',
      width: 100,
      align: 'center',
      sorter: false,
      render: (value, record, index) =>
        value === undefined ? (
          <Tag style={{ cursor: 'default' }} className={styles.label_primary}>
            未生成
          </Tag>
        ) : (
          <Tag style={{ cursor: 'default' }} className={styles.label_success}>
            已生成
          </Tag>
        ),
    },
    { title: '开始时间', dataIndex: 'startTime', width: 150, align: 'center', sorter: false },
    { title: '结束时间', dataIndex: 'endTime', width: 150, align: 'center', sorter: false },
    { title: '创建时间', dataIndex: 'createTime', width: 150, align: 'center', sorter: true },
    {
      title: '操作',
      dataIndex: '',
      width: 170,
      align: 'center',
      fixed: 'right',
      render: (value, record, index) => (
        <React.Fragment>
          <a
            hidden={!hasPermission('promotionrecommend:update')}
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.update();
            }}
          >
            <Tooltip title={<FormattedMessage id="ours.curd.list.edit" defaultMessage="编辑" />}>
              <Icon type="edit" />
            </Tooltip>
          </a>
          <Divider hidden={record.status === 0} type="vertical" />
          <a
            hidden={!hasPermission('promotionrecommend:info')}
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.view();
            }}
          >
            <Tooltip title={<FormattedMessage id="ours.curd.list.info" defaultMessage="查看" />}>
              <Icon type="info" />
            </Tooltip>
          </a>
          <Divider type="vertical" />
          <a
            hidden={!hasPermission('promotionrecommend:info')}
            onClick={() => {
              this.createWxImage(record, index);
            }}
          >
            <Tooltip
              title={
                <FormattedMessage id="ours.curd.list.createWxImage" defaultMessage="生成二维码" />
              }
            >
              <Icon type="file-image" />
            </Tooltip>
          </a>
          <Divider hidden={record.status === 0} type="vertical" />
          <a
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.showDrawer();
            }}
          >
            查看商品
          </a>
        </React.Fragment>
      ),
    },
    // {
    //   title: '状态',
    //   dataIndex: 'status',
    //   width: 30,
    //   align: 'center',
    //   fixed: 'right',
    //   render: (value, record, index) =>
    //     value === 0 ? (
    //       <Tag style={{ cursor: 'default' }} className={styles.label_success}>
    //         正常
    //       </Tag>
    //     ) : (
    //       <Tag style={{ cursor: 'default' }} className={styles.label_danger}>
    //         暂停
    //       </Tag>
    //     ),
    // },
  ];

  constructor(props) {
    super(props);
    this.state = {
      showList: 1, //1:显示列表、2:显示新增
      formList: Recommend.getFormList(),
      selectedRows: [],
      selectedIds: [],
      selectedIndexs: [],
      editModalTitle: null,
      editModalType: null,
      editModel: null,
      editModelConfirmLoading: false,
      //其他属性下面书写
    };
  }

  // 筛选条件
  static getFormList = () => [
    {
      type: 'INPUT',
      field: 'recommendName',
      label: '推荐有礼名称',
      placeholder: '推荐有礼名称',
    },
    {
      type: 'INPUT',
      field: 'status',
      label: '状态',
      placeholder: '状态',
    },
    {
      type: 'DATE_RANGE',
      field: 'startTime',
      label: '生效时间-开始',
      placeholder: ['生效时间-开始', ''],
    },
    {
      type: 'DATE_RANGE',
      field: 'endTime',
      label: '生效时间-结束',
      placeholder: ['生效时间-结束', ''],
    },
    {
      type: 'DATE_RANGE',
      field: 'createTime',
      label: '创建时间',
      placeholder: ['创建时间', ''],
    },
    //下面是各种组件的示例代码，不用 请删除不需要的代码和注释
    {
      type: 'SELECT',
      field: 'parentId',
      placeholder: '菜单目录',
      initialValue: '',
      list: [{ id: '', name: '请选择菜单目录' }],
      showSearch: true,
    },
  ];

  componentDidMount() {
    this.requestList();
  }

  componentWillUnmount() {}

  /**
   * 根据 formItem field 取值 查找formItem
   * @param formItemField obj的field字段
   * @returns 一个对象
   */
  findFormListItemByField = formItemField =>
    this.state.formList.find((value, index, array) => value.field === formItemField);

  query = fieldParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, fieldParams)));
    this.requestList();
  };

  add = () => {
    this.setState({
      editModalType: 'add',
      editModalTitle: formatMessage({ id: 'ours.curd.list.create' }), //创建
      editModel: {
        bgColor: '#5e72e4',
      },
      showList: 2,
    });
  };

  update = () => {
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }
    this.setState({
      editModalType: 'update',
      editModalTitle: <FormattedMessage id="ours.curd.list.edit" defaultMessage="编辑" />,
      editModel: JSON.parse(JSON.stringify(selectedRows[0])),
      showList: 2,
    });
    this.getInfo(selectedRows[0].recommendId);
  };

  view = () => {
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }
    this.setState({
      editModalType: 'view',
      editModalTitle: <FormattedMessage id="ours.curd.list.info" defaultMessage="查看" />,
      editModel: selectedRows[0],
      showList: 2,
    });
    this.getInfo(selectedRows[0].recommendId);
  };

  del = () => {
    const selectedRows = this.state.selectedRows;
    const recommendIds = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      recommendIds.push(selectedRows[i].recommendId);
    }

    uiUtils.showConfirm(formatMessage({ id: 'ours.curd.show-alert.confirm-delete' }), () => {
      this.setState({
        loading: true,
      });
      requestPromise(`${getWebPath()}promotionrecommend/delete`, {
        method: 'POST',
        body: recommendIds,
      }).then(res => {
        this.setState({
          loading: false,
        });
        if (res && res.code === 0) {
          uiUtils.showMessage(
            formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
            'success'
          );
          this.requestList();
        }
      });
    });
  };

  saveOrUpdate = () => {
    const editModalType = this.state.editModalType;
    //不能双向绑定，这里只能原对象、新对象进行合并.
    const promotionRecommend = Object.assign(
      this.state.editModel,
      this.editForm.props.form.getFieldsValue()
    );

    this.editForm.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        // submit the values
        const url =
          promotionRecommend.recommendId == null
            ? '/promotionrecommend/save'
            : '/promotionrecommend/update';
        //对象删除一个属性
        //delete promotionRecommend.xxxxPros;
        promotionRecommend.describe = promotionRecommend.describe.toHTML();
        promotionRecommend.bgColor = promotionRecommend.bgColor.hex;
        promotionRecommend.startTime = `${promotionRecommend.startTimeBetween[0].format(
          'YYYY-MM-DD'
        )} 00:00:00`;
        promotionRecommend.endTime = `${promotionRecommend.startTimeBetween[1].format(
          'YYYY-MM-DD'
        )} 23:59:59`;
        this.setState({
          editModelConfirmLoading: true,
        });
        requestPromise(getWebPath() + url, {
          method: 'POST',
          body: promotionRecommend,
        }).then(res => {
          this.setState({
            editModelConfirmLoading: false,
          });
          if (res && res.code === 0) {
            uiUtils.showMessage(
              formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
              'success'
            );
            this.setState({
              showList: 1,
            });

            //新增重新置为第一页
            if (!promotionRecommend.recommendId) {
              this.params.page = 1;
            }
            this.requestList();
          }
        });
      }
    });
  };

  getInfo = recommendId => {};

  setStateByTableColume = (record, index) => {
    this.state = {
      ...this.state,
      selectedRows: [record],
      selectedIds: [record.recommendId],
      selectedIndexs: [index],
    };
  };

  updateStatus = val => {
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }
    let status;
    if (val) {
      status = 1;
    } else {
      status = -1;
    }
    const ids = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      ids.push(selectedRows[i].recommendId);
    }

    this.setState({
      loading: true,
    });
    //const data = 'modelIds=' + ids.join(',') + '&status=' + status;
    const data = {
      modelIds: ids.join(','),
      status,
    };
    requestPromise(`${getWebPath()}promotionrecommend/operatePromotionRecommendByRecommendIds`, {
      method: 'POST',
      contentType: 'application/x-www-form-urlencoded',
      body: data,
    }).then(res => {
      this.setState({
        loading: false,
      });
      if (res && res.code === 0) {
        uiUtils.showMessage(
          formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
          'success'
        );
        this.requestList();
      }
    });
  };

  operateByIds = status => {
    //这里处理，发布、取消发布、删除、禁用等状态操作; 参数status由调用放传入
    // const {selectedRows, selectedIds, selectedIndexs} = this.state;
    // const ids = [];
    // for (let i = 0; i < selectedRows.length; i += 1) {
    //   ids.push(selectedRows[i].recommendId);
    // }
    //
    // /* eslint-disable no-param-reassign */
    // status = !status ? 3 : status;
    // let tips = "请确定是否要进行操作??????";
    // let msgIds = null;
    // if (status === 2) {
    //   msgIds = 'ours.curd.show-alert.confirm-publish';//发布
    // } else if (status === 3) {
    //   msgIds = 'ours.curd.show-alert.confirm-delete';//删除
    // } else if (status === 1) {
    //   tips = "请选择要撤消选中项吗？";
    //   msgIds = 'ours.curd.show-alert.confirm-enable';//启用
    // } else if (status === -1) {
    //   msgIds = 'ours.curd.show-alert.confirm-disable';//禁用
    // }
    //
    // uiUtils.showConfirm(formatMessage({id: msgIds}), () => {
    //   this.setState({
    //     loading: true,
    //   });
    //   //const data = 'modelIds=' + ids.join(',') + '&status=' + status;
    //   const data = {
    //     modelIds: ids.join(','),
    //     status,
    //   };
    //   requestPromise(`${getWebPath()}promotionrecommend/operatePromotionRecommendByRecommendIds`, {
    //     method: 'POST',
    //     contentType: "application/x-www-form-urlencoded",
    //     body: data,
    //   }).then(res => {
    //     this.setState({
    //       loading: false,
    //     });
    //     if (res && res.code === 0) {
    //       uiUtils.showMessage(
    //         formatMessage({id: 'ours.curd.show-alert.operate-success'}),
    //         'success'
    //       );
    //       this.requestList();
    //     }
    //   });
    // });
  };

  createWxImage = (record, index) => {
    //此处如果它的类型值为空， 为了不让下面的接口出现异常，这里传入-1， -1 在接口中也代表该值不存在
    if (record.wxQrCode) {
      uiUtils.showConfirm(formatMessage({ id: '已经存在二维码，是否再次生成？' }), () => {
        requestPromise(
          `${getWebPath(
            `/promotionrecommend/createWxImage?recommendId=${record.recommendId}`
          )}`,
          {
            method: 'GET',
          }
        ).then(res => {
          if (res && res.code === 0) {
            uiUtils.showMessage('操作成功');
            this.requestList();
          }
        });
      });
    } else {
      uiUtils.showConfirm(formatMessage({ id: '是否生成二维码？' }), () => {
        requestPromise(
          `${getWebPath(
            `/promotionrecommend/createWxImage?recommendId=${record.recommendId}`
          )}`,
          {
            method: 'GET',
          }
        ).then(res => {
          if (res && res.code === 0) {
            uiUtils.showMessage('操作成功');
            this.requestList();
          }
        });
      });
    }
  };

  showDrawer = () => {
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    this.setState({
      visible: true,
      productLoadingSpinning: true,
      recommendId: selectedRows[0].recommendId,
    });
    this.getProducts(selectedRows[0].recommendId);
  };

  onClose = () => {
    this.setState({
      visible: false,
    });
  };

  getProducts = recommendId => {
    requestPromise(
      `${getWebPath()}promotionrecommend/getProductByRecommendId?recommendId=${recommendId}`,
      {
        method: 'GET',
      }
    ).then(res => {
      if (res && res.code === 0) {
        this.setState({
          productDatas: res.datas,
          productLoadingSpinning: false,
        });
      }
    });
  };

  //========其他所有的处理方法，请在按照约定进行处理==========

  getProductLists = () => {
    this.setState({
      productLoading: true,
      productLists: [],
    });
    requestPromise(
      `${getWebPath()}mailproduct/listVo?sidx=id&order=asc&not_recommendId=${
        this.state.recommendId
      }`,
      {
        method: 'GET',
      }
    ).then(res => {
      this.setState({
        productLoading: false,
      });
      if (res && res.code === 0) {
        const datas = res.page.list;
        datas.forEach(d => {
          d.key = d.id;
        });
        this.setState({
          productLists: datas,
        });
      }
    });
  };

  showProduct = () => {
    this.getProductLists();
    this.setState({
      productVisible: true,
      selectedRowKeys: [],
    });
  };

  handleSearch = (selectedKeys, confirm) => {
    confirm();
    this.setState({ searchText: selectedKeys[0] });
  };

  handleReset = clearFilters => {
    clearFilters();
    this.setState({ searchText: '' });
  };

  getColumnSearchProps = dataIndex => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
      <div style={{ padding: 8 }}>
        <Input
          ref={node => {
            this.searchInput = node;
          }}
          placeholder="商品名称"
          value={selectedKeys[0]}
          onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => this.handleSearch(selectedKeys, confirm)}
          style={{ width: 188, marginBottom: 8, display: 'block' }}
        />
        <Button
          type="primary"
          onClick={() => this.handleSearch(selectedKeys, confirm)}
          icon="search"
          size="small"
          style={{ width: 90, marginRight: 8 }}
        >
          查询
        </Button>
        <Button onClick={() => this.handleReset(clearFilters)} size="small" style={{ width: 90 }}>
          重置
        </Button>
      </div>
    ),
    filterIcon: filtered => (
      <Icon type="search" style={{ color: filtered ? '#1890ff' : undefined }} />
    ),
    onFilter: (value, record) =>
      record[dataIndex]
        .toString()
        .toLowerCase()
        .includes(value.toLowerCase()),
    onFilterDropdownVisibleChange: visible => {
      if (visible) {
        setTimeout(() => this.searchInput.select());
      }
    },
    render: text => (
      <Highlighter
        highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
        searchWords={[this.state.searchText]}
        autoEscape
        textToHighlight={text.toString()}
      />
    ),
  });

  submitProduct = () => {
    this.setState({
      confirmLoading: true,
    });
    const recommendId = this.state.recommendId;
    const productIds = this.state.productIds;
    const data = {
      recommendId,
      productIds,
    };
    requestPromise(
      `${getWebPath()}promotionrecommend/addProduct?recommendId=${recommendId}&productIds=${productIds}`,
      {
        method: 'GET',
        // contentType: "application/x-www-form-urlencoded",
      }
    ).then(res => {
      this.setState({
        confirmLoading: false,
        productVisible: false,
      });
      if (res && res.code === 0) {
        uiUtils.showMessage(
          formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
          'success'
        );
        this.getProducts(recommendId);
      }
    });
  };

  deleteProduct = productId => {
    requestPromise(
      `${getWebPath()}promotionrecommend/deleteProduct?productId=${productId}&recommendId=${
        this.state.recommendId
      }`,
      {
        method: 'GET',
        // contentType: "application/x-www-form-urlencoded",
      }
    ).then(res => {
      if (res && res.code === 0) {
        uiUtils.showMessage(
          formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
          'success'
        );
        this.getProducts(this.state.recommendId);
      }
    });
  };

  onSelectChange = (selectedRowKeys, selectedRows) => {
    this.setState({
      productIds: selectedRowKeys,
    });
    this.setState({ selectedRowKeys });
  };

  /**
   * 表格 筛选和排序 回调
   */
  filtersSorterChange = tableParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, tableParams)));
    this.requestList();
  };

  requestList = () => {
    requestLists(this, `${getWebPath()}promotionrecommend/list`, this.params);
  };

  vShow = showListNum => ({ display: this.state.showList === showListNum ? 'block' : 'none' });

  render() {
    const style = {
      style: {
        marginLeft: 10,
        marginTop: 10,
      },
      disabled: this.state.selectedIndexs.length <= 0,
    };
    const { selectedRowKeys } = this.state;

    const CardInfo = ({ productId, price }) => (
      <div style={{ marginTop: 5 }}>
        <div>
          <span style={{ float: 'left' }}>￥ {price}</span>
          <span style={{ float: 'right' }}>
            <a
              onClick={() => {
                this.deleteProduct(productId);
              }}
            >
              <Tooltip placement="bottom" title="删除">
                <Icon type="close" />
              </Tooltip>
            </a>
          </span>
        </div>
      </div>
    );

    const productColumns = [
      {
        title: '商品名称',
        dataIndex: 'productName',
        width: 100,
        align: 'center',
        ...this.getColumnSearchProps('productName'),
      },
      {
        title: '封面图',
        dataIndex: 'images',
        width: 90,
        align: 'center',
        sorter: false,
        render: (value, record, index) => (
          <DefaultImage
            src={`${value}`.includes(',') ? value.split(',')[0] : `${value}`}
            alt=""
            width="50px"
            height="50px"
          />
        ),
      },
      {
        title: '价格',
        dataIndex: 'price',
        width: 105,
        align: 'center',
        sorter: false,
        render: value => {
          let formatCondition = '-';
          if (value !== null && value !== undefined) {
            formatCondition = `￥${numeral(value).format('0,0.00')}`;
          }
          return formatCondition;
        },
      },
    ];

    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };

    /* eslint-disable react/jsx-no-bind */
    return (
      <PageHeaderWrapper title="">
        <Card
          bordered={false}
          style={{ ...this.vShow(1) }}
          className={styles.oursCard}
          bodyStyle={{ padding: '20px' }}
        >
          <BaseForm
            formList={this.state.formList}
            loading={this.state.loading}
            filterSubmit={this.query}
          />

          <Fragment>
            <Button
              type="primary"
              icon="plus"
              onClick={this.add}
              hidden={!hasPermission('promotionrecommend:save')}
            >
              <FormattedMessage id="ours.curd.list.add" defaultMessage="新增" />
            </Button>
            <Button
              type="danger"
              icon="delete"
              {...style}
              onClick={this.del}
              hidden={!hasPermission('promotionrecommend:delete')}
            >
              <FormattedMessage id="ours.curd.list.delete" defaultMessage="删除" />
            </Button>
          </Fragment>

          <div className="content-wrap">
            <ETable
              onSelectRow={uiUtils.onSelectRow.bind(this)}
              primaryKey="recommend_id"
              selectedRows={this.state.selectedRows}
              selectedIds={this.state.selectedIds}
              selectedIndexs={this.state.selectedIndexs}
              onChange={this.filtersSorterChange}
              columns={this.columns}
              dataSource={this.state.list}
              pagination={this.state.pagination}
              loading={this.state.loading}
              scroll={{ x: 1580 }}
            />
          </div>
        </Card>

        <BackTop />

        <Spin spinning={this.state.editModelConfirmLoading} delay={10}>
          {//返回null,这里对不用的组件进行销毁
          this.state.showList === 1 ? null : (
            <Card
              title={this.state.editModalTitle}
              bordered={false}
              actions={[
                <div>
                  <React.Fragment>
                    <Button
                      type="primary"
                      hidden={this.state.editModalType === 'view'}
                      style={{ marginRight: '18px' }}
                      onClick={this.saveOrUpdate}
                    >
                      <FormattedMessage id="ours.curd.add.save" defaultMessage="保存" />
                    </Button>
                    <Button
                      style={{ marginRight: '18px' }}
                      onClick={() => {
                        this.editForm.props.form.resetFields();
                        this.setState({ showList: 1 });
                      }}
                    >
                      <FormattedMessage id="ours.curd.add.back" defaultMessage="返回" />
                    </Button>
                  </React.Fragment>
                </div>,
              ]}
              style={{ ...this.vShow(2) }}
              bodyStyle={{ padding: '20px' }}
              ref={node => {
                this.container = node;
              }}
            >
              <EditForm
                type={this.state.editModalType}
                model={this.state.editModel}
                wrappedComponentRef={inst => {
                  this.editForm = inst;
                }}
              />
            </Card>
          )}
        </Spin>

        {/*选择商品对话框*/}
        <Modal
          width={700}
          height={500}
          visible={this.state.productVisible}
          title="选择商品"
          onCancel={() => {
            this.setState({
              productVisible: false,
            });
          }}
          onOk={this.submitProduct}
          confirmLoading={this.state.confirmLoading}
          saveDistance={0}
          destroyOnClose
        >
          <div className="content-wrap">
            <Table
              loading={this.state.productLoading}
              rowSelection={rowSelection}
              columns={productColumns}
              dataSource={this.state.productLists}
              size="small"
            />
          </div>
        </Modal>

        {/*商品信息抽屉*/}
        <Drawer
          title="商品信息"
          placement="right"
          closable={false}
          onClose={this.onClose}
          visible={this.state.visible}
          width={600}
          extra={<a href="#">More</a>}
        >
          <Spin spinning={this.state.productLoadingSpinning} delay={10}>
            <List
              grid={{ gutter: 16, column: 3 }}
              dataSource={this.state.productDatas}
              renderItem={item => (
                <List.Item>
                  <Card
                    hoverable
                    bodyStyle={{ paddingBottom: 10 }}
                    style={{ width: 150 }}
                    // title={item.productName}
                    // extra={<a href="#"><Icon type="close" /></a>}
                    cover={
                      <DefaultImage
                        src={
                          `${item.images}`.includes(',')
                            ? item.images.split(',')[0]
                            : `${item.images}`
                        }
                        alt={item.productName}
                        width={200}
                        height={100}
                      />
                    }
                  >
                    {/*<Card.Meta title="" description={item.productName} />*/}
                    <Ellipsis length={10} tooltip>
                      {item.productName}
                    </Ellipsis>
                    <CardInfo price={item.price} productId={item.id} />
                  </Card>
                </List.Item>
              )}
            />
          </Spin>
          <div
            style={{
              position: 'absolute',
              bottom: 0,
              width: '100%',
              borderTop: '1px solid #e8e8e8',
              padding: '10px 16px',
              textAlign: 'left',
              left: 0,
              background: '#fff',
              borderRadius: '0 0 4px 4px',
            }}
          >
            <Button type="primary" icon="plus" onClick={this.showProduct}>
              添加商品
            </Button>
          </div>
        </Drawer>
      </PageHeaderWrapper>
    );
  }
}

export default Recommend;

/**
 *  新增、编辑、复制、查看的Form
 */

/* eslint react/no-multi-comp:0 */
class EditForm extends React.Component {
  static propTypes = {
    type: PropTypes.string, //form类型，可选值：add（增加）、update（修改）、copy（复制）、view（查看）、
    model: PropTypes.object, //数据模型model，对应后台的model
  };

  static defaultProps = {
    type: '', //表单布局数组
    model: null,
  };

  constructor(props) {
    super(props);
    this.getGiftLists();
    const defaultImgList = this.props.model.img
      ? [
          {
            uid: '1',
            name: '',
            status: 'done',
            url: this.props.model.img,
          },
        ]
      : null; //defaultFileList
    this.state = {
      previewImgVisible: false, //上传文件预览
      previewImg: '', //上传文件预览
      defaultImgList, //上传文件列表
      imgList: defaultImgList && defaultImgList.length > 0 ? [defaultImgList[0]] : [],
    };
  }

  /**
   * 生命周期-属性发生变化...componentWillReceiveProps
   * 这里的nextProps，可以获取到所有的属性。
   * 目前没用，因为 dialog 每次都被销毁了
   */
  componentWillReceiveProps(nextProps) {
    if (nextProps.model) {
      // this.state = {};
      //使用setFieldsValue实现修改form value的值，不用使用 this.setState({});
      // this.props.model.xxx = 'value';
      // this.props.form.setFieldsValue({xxx: 'value'});
    }
  }

  getPropsByKey = prop => {
    const model = this.props.model || {};
    const finalModel = Object.assign(model, this.props.form.getFieldsValue());
    return finalModel[prop];
  };

  handleUploadImgOnRemove = file => {
    //只上传一文件，这里偷懒
    this.setState({
      imgList: [],
      defaultImgList: null,
    });
  };

  handleUploadImgOnChange = info => {
    const { loadingCallback } = this.props;
    // 状态有：uploading done error removed
    if (info.file.status === 'done') {
      //这个Upload组件比较特殊，这里在OnChange方法手工设置value,不做延迟，就设置不了被覆盖了。
      const response = info.fileList[0].response;
      this.setState({
        imgList: info.fileList,
      });
      if (response) {
        if (response.code === 0) {
          uiUtils.showMessage(`${info.file.name} 文件上传成功.`, 'success');
          setTimeout(() => {
            this.props.form.setFieldsValue({
              img: response.object,
            });
            if (loadingCallback) {
              loadingCallback(false);
            }
          }, 500);
        } else {
          uiUtils.showAlert(response.msg, 'error');
          if (loadingCallback) {
            loadingCallback(false);
          }
        }
      }
    } else if (info.file.status === 'error') {
      if (loadingCallback) {
        loadingCallback(false);
      }
      uiUtils.showMessage(`${info.file.name} 文件上传失败.`, 'error');
    } else if (info.file.status === 'uploading') {
      if (loadingCallback) {
        loadingCallback(true);
      }
    }
  };

  getGiftLists = () => {
    requestPromise(`${getWebPath()}promotiongift/getGiftList`, {
      method: 'GET',
    }).then(res => {
      if (res && res.code === 0) {
        const datas = [];
        res.datas.forEach(d => {
          if (d.id !== this.props.model.giftId) {
            datas.push(
              <Option key={d.id} value={d.id}>
                {d.giftName}
              </Option>
            );
          }
        });
        this.setState({
          giftLists: datas,
        });
      }
    });
  };

  preview = () => {
    editorPreview(this.state.editorState.toHTML());
  };

  handleChange = editorState => {
    this.setState({ editorState });
  };

  render() {
    const type = this.props.type; //编辑是：新增（add）、编辑(edit)、复制(copy)、还是查看(view)
    const model = this.props.model || {};
    const {
      form,
      form: { getFieldDecorator, getFieldValue, setFieldsValue },
    } = this.props;
    const formItemLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 18 }, //5+19=24,少一个栅格
    };
    const formItemLayoutV1 = {
      labelCol: { span: 3 },
      wrapperCol: { span: 18 }, //5+19=24,少一个栅格
    };
    const colSpanLayout = { md: 12, sm: 24 }; //每一col跨?列
    const rowGutterPxLayout = { md: 24, sm: 16 }; //col之间的间隔?px
    const inputCodeDisabled = {
      disabled: type === 'update',
    };

    const inputCodeDisabledForView = {
      disabled: type === 'view',
    };

    const imageCoverProps = {
      action: `${getWebPath('/api/fileUpload')}`,
      name: 'myfile',
      data: { moduleName: 'recommend', isImage: false, acceptFileExts: 'image'  },
      withCredentials: true,
      headers: {
        authorization: 'authorization-text',
      },
      onChange: this.handleUploadImgOnChange,
      onRemove: this.handleUploadImgOnRemove,
      defaultFileList: this.state.defaultImgList,
      multiple: false,
      accept: '.jpg, .jpeg, .png, .bmp, ',
    };

    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传</div>
      </div>
    );

    const result = [];
    if (type === 'update' || type === 'view') {
      result.push(
        <Option key={model.giftId} value={model.giftId}>
          {model.giftName}
        </Option>
      );
    }

    const extendControls = [
      {
        key: 'custom-button',
        type: 'button',
        text: '预览',
        onClick: this.preview,
      },
    ];

    const editorProps = {
      height: 500,
      media: {
        uploadFn: handleEditorupload,
      },
      imageControls: [],
      fontFamilies: [],
    };

    //校验文档：https://ant.design/components/form-cn/#%E6%A0%A1%E9%AA%8C%E8%A7%84%E5%88%99
    return (
      <Form layout="horizontal">
        <Row gutter={{ ...rowGutterPxLayout }}>
          <Col {...colSpanLayout}>
            <FormItem label="赠品" {...formItemLayout}>
              {getFieldDecorator('giftId', {
                initialValue: model.giftId,
                rules: [
                  {
                    required: true,
                    message: '赠品必填',
                  },
                ],
              })(
                <Select
                  showSearch
                  style={{ width: 330 }}
                  placeholder="请选择赠品"
                  optionFilterProp="children"
                  {...inputCodeDisabledForView}
                  // onChange={this.productChange}
                  // onFocus={this.productSearch}
                  onSearch={this.productSearch}
                  notFoundContent={null}
                >
                  {result}
                  {this.state.giftLists}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="推荐有礼名称" {...formItemLayout}>
              {getFieldDecorator('recommendName', {
                initialValue: model.recommendName,
                rules: [
                  {
                    required: true,
                    message: '推荐有礼名称必填',
                  },
                  {
                    whitespace: true,
                    message: '不能包含空白符',
                  },
                  {
                    max: 128,
                    message: '最长128个字符',
                  },
                ],
              })(
                <Input
                  type="text"
                  autocomplete="off"
                  style={{ width: '330px' }}
                  maxlength={128}
                  {...inputCodeDisabledForView}
                  placeholder="推荐有礼名称"
                />
              )}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem
              label="图片"
              {...formItemLayout}
              extra="文件尺寸建议750 x 400, 支持jpg、png、gif格式!"
            >
              {getFieldDecorator('img', {
                initialValue: model.img,
                rules: [
                  {
                    required: true,
                    message: '图片必填',
                  },
                ],
              })(
                <div className="clearfix">
                  <Upload
                    {...imageCoverProps}
                    listType="picture-card"
                    {...inputCodeDisabledForView}
                  >
                    {this.state.imgList && this.state.imgList.length >= 1 ? null : uploadButton}
                  </Upload>
                  <Modal
                    visible={this.state.previewImgVisible}
                    footer={null}
                    onCancel={() => this.setState({ previewImgVisible: false })}
                  >
                    <img
                      alt="imgExample"
                      style={{ width: '100%' }}
                      src={this.state.previewImg}
                      {...inputCodeDisabledForView}
                    />
                  </Modal>
                </div>
              )}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="背景颜色" {...formItemLayout}>
              {getFieldDecorator('bgColor', {
                initialValue: model.bgColor,
                rules: [
                  {
                    required: true,
                    message: '背景颜色必填',
                  },
                ],
              })(<InputColor initialHexColor={model.bgColor} placement="right" />)}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="有效时间" {...formItemLayout}>
              {getFieldDecorator('startTimeBetween', {
                initialValue: [
                  moment(model.startTime === undefined ? moment() : model.startTime, 'YYYY/MM/DD'),
                  moment(model.endTime === undefined ? moment() : model.endTime, 'YYYY/MM/DD'),
                ],
                rules: [
                  {
                    required: true,
                    message: '有效时间',
                  },
                ],
              })(
                <RangePicker
                  {...inputCodeDisabledForView}
                  defaultValue={[
                    moment(
                      model.startTime === undefined ? moment() : model.startTime,
                      'YYYY/MM/DD'
                    ),
                    moment(model.endTime === undefined ? moment() : model.endTime, 'YYYY/MM/DD'),
                  ]}
                  style={{ width: '330px' }}
                />
              )}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="租户" {...formItemLayout}>
              {getFieldDecorator('tenantid', {
                initialValue: model.tenantid === undefined ? 1 : model.tenantid,
                rules: [
                  {
                    required: true,
                    message: '必填,默认为1',
                  },
                  rulesReg('number'),
                ],
              })(
                <Input
                  {...inputCodeDisabledForView}
                  type="text"
                  autocomplete="off"
                  style={{ width: '330px' }}
                  disabled
                  placeholder="tenantId"
                />
              )}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="微信二维码" {...formItemLayout}>
              {getFieldDecorator('wxQrCode', {
                initialValue: model.wxQrCode,
                rules: [],
              })(
                <div className="clearfix">
                  <DefaultImage style={{ width: '50%', height: '50%' }} src={model.wxQrCode} />
                </div>
              )}
            </FormItem>
          </Col>
        </Row>
        <Card
          bordered
          hoverable
          size="small"
          bodyStyle={{ paddingBottom: 10 }}
          style={{ marginBottom: 20 }}
          title="介绍"
        >
          {getFieldDecorator('describe', {
            initialValue: BraftEditor.createEditorState(model.describe),
            rules: [
              {
                required: false,
                message: '介绍必填',
              },
            ],
          })(
            <BraftEditor
              className={styles.my_editor}
              placeholder="请输入介绍"
              onChange={this.handleChange}
              extendControls={extendControls}
              {...inputCodeDisabledForView}
              {...editorProps}
            />
          )}
        </Card>
      </Form>
    );
  }
}

/* eslint-disable no-class-assign */
//无更多的绑定， 请用 @Form.create() 注解替换
EditForm = Form.create({})(EditForm);
